<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!--   禁用id搜索   -->
      <!--      <el-form-item label="管理员" prop="adminId">
        <el-input
          v-model="queryParams.adminId"
          placeholder="请输入管理员"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>-->
      <el-form-item label="账号" prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入账号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!--  禁用密码搜索    -->
      <!--      <el-form-item label="密码" prop="password">
        <el-input
          v-model="queryParams.password"
          placeholder="请输入密码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>-->
      <el-form-item label="权限字符" prop="role" style="width: 250px">
<!--        <el-input v-model="queryParams.role" placeholder="请输入权限字符" clearable @keyup.enter="handleQuery" />-->
        <el-select
            v-model="queryParams.role"
            placeholder="请选择权限字符"
            clearable
            @change="handleQuery"
        >
          <el-option
              v-for="item in roleStrOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!--   禁用默认生成的   -->
      <!--      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>-->
      <el-form-item label="时间范围" style="width: 308px">
        <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['admin:admin:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['admin:admin:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['admin:admin:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['admin:admin:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="adminList" @selection-change="handleSelectionChange" stripe>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="管理员id" align="center" prop="adminId" />
<!--      <el-table-column label="账号" align="center" prop="username" />-->
      <el-table-column label="账号" align="center" prop="username" width="100" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ scope.row.username }}{{ scope.row.status === '1' ? '(停用)' : '' }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="密码" align="center" prop="password" />-->
      <el-table-column label="账号状态" align="center" prop="status">
        <template #default="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="权限字符" align="center" prop="role" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span v-if="scope.row?.updateTime && scope.row.updateTime.trim() !== ''">
            {{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </span>
          <span v-else>
            未更新
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['admin:admin:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['admin:admin:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改系统管理员对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="adminRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入账号" :disabled="form.adminId !== null" />
        </el-form-item>
        <!--        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>-->
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限字符" prop="role">
<!--          <el-input v-model="form.role" placeholder="请输入权限字符" />-->
          <el-select
              v-model="form.role"
              placeholder="请选择权限字符"
              clearable
          >
            <el-option
                v-for="item in roleStrOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Admin">
import { listAdmin, getAdmin, delAdmin, addAdmin, updateAdmin, changeAdminStatus } from "@/api/admin/admin"
import { nextTick } from 'vue'
import { parseTime } from "../../../utils/ruoyi.js"; // 引入 nextTick

const { proxy } = getCurrentInstance()

const adminList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 添加初始化标记
const isInitialized = ref(false)
//日期范围
const dateRange = ref([])
const roleStrOptions = ref([
  { label: 'super_admin', value: 'super_admin' },
  { label: 'admin', value: 'admin' },
  { label: 'common', value: 'common' }
])


const { sys_normal_disable } = proxy.useDict("sys_normal_disable")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    adminId: null,
    username: null,
    password: null,
    status: null,
    role: null,
    beginTime: null,
    endTime: null
  },
  rules: {
    username: [
      { required: true, message: "账号不能为空", trigger: "blur" }
    ],
    role: [
      { required: true, message: "权限字符不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询系统管理员列表 */
function getList() {
  loading.value = true
  isInitialized.value = false

  // 确保传递正确的查询参数
  listAdmin(queryParams.value).then(response => {
    adminList.value = response.rows
    total.value = response.total
    loading.value = false

    nextTick(() => {
      isInitialized.value = true
    })
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    adminId: null,
    username: null,
    password: null,
    status: null,
    role: null,
  }
  proxy.resetForm("adminRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  console.log(dateRange.value)
  // 设置日期范围参数
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.beginTime = dateRange.value[0];
    queryParams.value.endTime = `${dateRange.value[1]} 23:59:59`;
  } else {
    queryParams.value.beginTime = null;
    queryParams.value.endTime = null;
  }
  console.log(queryParams.value)
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  // 重置日期参数
  queryParams.value.beginTime = null
  queryParams.value.endTime = null
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.adminId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  /*form.value = {
    status: '0',  // 默认启用状态
  }*/
  form.value.status = '0' // 默认启用状态
  open.value = true
  title.value = "添加系统管理员"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _adminId = row.adminId || ids.value
  getAdmin(_adminId).then(response => {
    form.value = response.data
    /*// 新增：强制转换状态值为字符串类型
    if (form.value.status !== null && form.value.status !== undefined) {
      form.value.status = String(form.value.status);
    }*/
    open.value = true
    title.value = "修改系统管理员"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["adminRef"].validate(valid => {
    if (valid) {
      if (form.value.adminId != null) {
        updateAdmin(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addAdmin(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _adminIds = row.adminId || ids.value
  proxy.$modal.confirm('是否确认删除系统管理员编号为"' + _adminIds + '"的数据项？').then(function () {
    return delAdmin(_adminIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('admin/admin/export', {
    ...queryParams.value
  }, `admin_${new Date().getTime()}.xlsx`)
}

/** 用户状态修改  */
function handleStatusChange(row) {
  // 若未初始化，不触发弹窗
  if (!isInitialized.value) return // 新增此行
  let text = row.status === "0" ? "启用" : "停用"
  proxy.$modal.confirm(`确认要${text}"${row.username}"管理员吗?`).then(() => {
    return changeAdminStatus(row.adminId, row.status)
  }).then(() => {
    proxy.$modal.msgSuccess(`${text}成功`)
  }).catch(() => {
    // 操作失败时回滚状态
    row.status = row.status === "0" ? "1" : "0"
  })
}

getList()

</script>
